package home.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.bumptech.glide.Glide;
import com.example.xfengshopping.MainActivity;
import com.example.xfengshopping.R;
import com.example.xfengshopping.WelcomeActivity;
import utils.TokenUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import LOGIN.login;

public class GoodsDetailActivity extends AppCompatActivity {
    private static final String TAG = "GoodsDetailActivity";
    private static final int SUCCESS = 1;
    private static final int FAILURE = 2;
    private static final int UNAUTHORIZED = 3;

    private Toolbar toolbar;
    private TextView tvName, tvIntro, tvPrice;
    private ImageView ivCover, ivDetailImage;
    private TextView btnAddToCart, btnBuyNow; // 改为TextView类型
    private int goodsId;
    private ProgressDialog progressDialog;

    private final Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }

            switch (msg.what) {
                case SUCCESS:
                    GoodsDetail data = (GoodsDetail) msg.obj;
                    updateUI(data);
                    break;
                case FAILURE:
                    Toast.makeText(GoodsDetailActivity.this, "获取商品详情失败", Toast.LENGTH_SHORT).show();
                    finish();
                    break;
                case UNAUTHORIZED:
                    Toast.makeText(GoodsDetailActivity.this, "请先登录", Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(GoodsDetailActivity.this, WelcomeActivity.class));
                    finish();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_detail);

        initViews();
        parseIntent();

        if (goodsId <= 0) {
            Toast.makeText(this, "商品ID无效", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        showLoading();
        fetchGoodsDetail();
    }

    private void initViews() {
        toolbar = findViewById(R.id.toolbar);
        tvName = findViewById(R.id.tv_goods_detail_name);
        tvIntro = findViewById(R.id.tv_goods_detail_intro);
        tvPrice = findViewById(R.id.tv_goods_detail_price);
        ivCover = findViewById(R.id.iv_goods_detail_cover);
        ivDetailImage = findViewById(R.id.iv_goods_detail_content);

        // 改为TextView类型，与布局文件中的控件匹配
        btnAddToCart = findViewById(R.id.btn_add_to_cart);
        btnBuyNow = findViewById(R.id.btn_buy_now);

        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        toolbar.setNavigationOnClickListener(v -> {
            // 点击返回图标时返回主页面
            Intent intent = new Intent(GoodsDetailActivity.this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); // 确保回到主页面栈顶
            startActivity(intent);
            finish(); // 关闭当前页面
        });
        
        btnAddToCart.setOnClickListener(this::addToCart);
        btnBuyNow.setOnClickListener(this::buyNow);
        findViewById(R.id.goshp).setOnClickListener(v -> {
            // 跳转至购物车页面（需根据实际项目结构调整）
            Intent intent = new Intent(GoodsDetailActivity.this, MainActivity.class);
            // 假设MainActivity中通过FragmentManager显示ShoppingcartFragment
            intent.putExtra("show_cart_fragment", true); // 可选：传递标识用于显示购物车Fragment
            startActivity(intent);
        });
    }

    private void parseIntent() {
        Intent intent = getIntent();
        if (intent != null && intent.hasExtra("goodsId")) {
            goodsId = intent.getIntExtra("goodsId", -1);
            Log.d(TAG, "Received goodsId: " + goodsId);
        } else {
            Log.e(TAG, "No goodsId found in intent");
            finish();
        }
    }

    private void showLoading() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("加载商品信息...");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    private void fetchGoodsDetail() {
        new Thread(() -> {
            HttpURLConnection connection = null;
            BufferedReader reader = null;

            try {
                String urlString = "http://47.99.134.126:28019/api/v1/goods/detail/" + goodsId;
                Log.d(TAG, "Request URL: " + urlString);

                URL url = new URL(urlString);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(10000);
                connection.setReadTimeout(10000);

                String token = TokenUtils.getToken(GoodsDetailActivity.this);

                if (!token.isEmpty()) {
                    connection.setRequestProperty("token", token);
                    Log.d(TAG, "Using token: " + token);
                } else {
                    handler.sendEmptyMessage(UNAUTHORIZED);
                    return;
                }

                int responseCode = connection.getResponseCode();
                Log.d(TAG, "Response code: " + responseCode);

                if (responseCode == HttpURLConnection.HTTP_OK) {
                    InputStream inputStream = connection.getInputStream();
                    reader = new BufferedReader(new InputStreamReader(inputStream));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    Log.d(TAG, "Response: " + response.toString());

                    JSONObject jsonObject = new JSONObject(response.toString());
                    int resultCode = jsonObject.getInt("resultCode");

                    if (resultCode == 200) {
                        JSONObject data = jsonObject.getJSONObject("data");
                        GoodsDetail goodsDetail = parseGoodsDetail(data);
                        handler.sendMessage(handler.obtainMessage(SUCCESS, goodsDetail));
                    } else if (resultCode == 401 || resultCode == 416) {
                        handler.sendEmptyMessage(UNAUTHORIZED);
                    } else {
                        handler.sendEmptyMessage(FAILURE);
                    }
                } else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
                    handler.sendEmptyMessage(UNAUTHORIZED);
                } else {
                    handler.sendEmptyMessage(FAILURE);
                }
            } catch (IOException | JSONException e) {
                Log.e(TAG, "Error: " + e.getMessage());
                handler.sendEmptyMessage(FAILURE);
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        Log.e(TAG, "Error closing reader: " + e.getMessage());
                    }
                }
            }
        }).start();
    }

    private GoodsDetail parseGoodsDetail(JSONObject data) throws JSONException {
        GoodsDetail detail = new GoodsDetail();
        detail.goodsId = data.getInt("goodsId");
        detail.goodsName = data.getString("goodsName");
        detail.goodsIntro = data.getString("goodsIntro");
        detail.goodsCoverImg = data.getString("goodsCoverImg");
        detail.sellingPrice = data.getDouble("sellingPrice");
        detail.goodsDetailContent = data.getString("goodsDetailContent");
        return detail;
    }

    private void updateUI(GoodsDetail data) {
        tvName.setText(data.goodsName);
        tvIntro.setText(data.goodsIntro);
        tvPrice.setText(String.format("¥%.2f", data.sellingPrice));

        Glide.with(this)
                .load(data.goodsCoverImg)
                .placeholder(R.drawable.ic_placeholder)
                .error(R.drawable.ic_error)
                .into(ivCover);

        String detailImageUrl = extractImageUrlFromHtml(data.goodsDetailContent);
        if (!detailImageUrl.isEmpty()) {
            Glide.with(this)
                    .load(detailImageUrl)
                    .placeholder(R.drawable.ic_placeholder)
                    .error(R.drawable.ic_error)
                    .into(ivDetailImage);
        }
    }

    private String extractImageUrlFromHtml(String html) {
        try {
            int start = html.indexOf("src=\"") + 5;
            int end = html.indexOf("\"", start);
            if (start > 0 && end > start) {
                return html.substring(start, end);
            }
        } catch (Exception e) {
            Log.e(TAG, "Error parsing image URL: " + e.getMessage());
        }
        return "";
    }

    private void addToCart(View view) {
        updateToCart();
        Toast.makeText(this, "已加入购物车", Toast.LENGTH_SHORT).show();
    }

    //加入购物车方法
// 1. 首先正确定义响应类（放在GoodsDetailActivity类内部）
    private static class CartResponse {
        int responseCode;
        String responseBody;

        CartResponse(int code, String body) {
            this.responseCode = code;
            this.responseBody = body;
        }
    }
    private static String readStream(InputStream inputStream) throws IOException {
        StringBuilder response = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        }
        return response.toString();
    }
    // 2. 修改updateToCart方法
    private void updateToCart() {
        String token = TokenUtils.getToken(this);
        if (token.isEmpty()) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            startActivity(new Intent(this, LOGIN.login.class));
            return;
        }

        btnAddToCart.setEnabled(false);

        new AsyncTask<Void, Void, CartResponse>() {  // 使用CartResponse
            @Override
            protected CartResponse doInBackground(Void... voids) {
                try {
                    JSONObject requestBody = new JSONObject();
                    requestBody.put("goodsId", goodsId);
                    requestBody.put("goodsCount", 1);

                    Log.d(TAG, "Request body: " + requestBody.toString());

                    return makeRequest("POST", "http://47.99.134.126:28019/api/v1/shop-cart",
                            token, requestBody.toString());
                } catch (JSONException e) {
                    Log.e(TAG, "JSON error", e);
                    return new CartResponse(500, "请求体构建失败");
                }
            }

            @Override
            protected void onPostExecute(CartResponse response) {  // 参数类型改为CartResponse
                btnAddToCart.setEnabled(true);
                Log.d(TAG, "API Response: " + response.responseCode + " - " + response.responseBody);

                try {
                    JSONObject jsonResponse = new JSONObject(response.responseBody);
                    int resultCode = jsonResponse.getInt("resultCode");

                    if (resultCode == 200) {
                        Toast.makeText(GoodsDetailActivity.this,
                                jsonResponse.optString("message", "已加入购物车"),
                                Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(GoodsDetailActivity.this,
                                "操作失败: " + jsonResponse.optString("message"),
                                Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    Toast.makeText(GoodsDetailActivity.this,
                            "响应解析错误", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, "Response parse error", e);
                }
            }
        }.execute();
    }

    // 3. 修改makeRequest方法
    private static CartResponse makeRequest(String method, String urlString, String token, String requestBody) {
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL(urlString);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod(method);
            urlConnection.setRequestProperty("token", token);
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setConnectTimeout(10000);

            if (requestBody != null) {
                urlConnection.setDoOutput(true);
                try (OutputStream os = urlConnection.getOutputStream()) {
                    os.write(requestBody.getBytes(StandardCharsets.UTF_8));
                }
            }

            int responseCode = urlConnection.getResponseCode();
            String responseBody = readStream(responseCode == 200 ?
                    urlConnection.getInputStream() :
                    urlConnection.getErrorStream());

            return new CartResponse(responseCode, responseBody);
        } catch (IOException e) {
            Log.e(TAG, "Network error", e);
            return new CartResponse(500, "网络请求失败");  // 这里也改为CartResponse
        } finally {
            if (urlConnection != null) urlConnection.disconnect();
        }
    }
    /// ///////////////////////////////////////////

    private void buyNow(View view) {
        Toast.makeText(this, "立即购买", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    private static class GoodsDetail {
        int goodsId;
        String goodsName;
        String goodsIntro;
        String goodsCoverImg;
        double sellingPrice;
        String goodsDetailContent;
    }
}